package com.chcit.handmedicine.database.service;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.chcit.handmedicine.database.model.LoginInfo;

public class LoginInfoService extends BaseService {

	private static final String SQL_CREATE_TABLE = 
			"create table if not exists logininfo " +
			"(id integer primary key autoincrement," +
			"username text not null," +
			"password text," +
			"last_login_time text," +
			"remember_password_flag text," +
			"auto_login_flag text);";

	private static final String SQL_DROP_TABLE = 
			"drop table if exists logininfo";
	
	private final String TABLE_NAME = "LoginInfo";
	
	public LoginInfoService(Context ctx) {
		super(ctx, SQL_CREATE_TABLE, SQL_DROP_TABLE);
//		onUpgrade(_db, 0, 1);
	}
	
	public LoginInfo getFirst() {
		LoginInfo loginInfo = null;
		Cursor result = _db.query("LoginInfo", 
				new String[] { 
					"id", 
					"username",
					"password", 
					"last_login_time", 
					"remember_password_flag",
					"auto_login_flag" }, 
				null, null, null, null, null, null);
		if (result != null && result.getCount() > 0) {
			result.moveToFirst();
			loginInfo = new LoginInfo(result);
		}
		result.close();
		return loginInfo;
	}

	public boolean update(LoginInfo loginInfo) {
		
		if (this.getFirst() == null) {
			return insert(loginInfo);
		} else {
			ContentValues data = new ContentValues();
			data.put("username", loginInfo.getUsername());
			data.put("password", loginInfo.getPassword());
			data.put("last_login_time", loginInfo.getLast_login_time());
			data.put("remember_password_flag", loginInfo.getRemember_password_flag());
			data.put("auto_login_flag", loginInfo.getAuto_login_flag());
			return _db.update(TABLE_NAME, data, "id=?",
					new String[] { String.valueOf(loginInfo.getId()) }) > 0;
		}
	}
	
	public boolean insert(LoginInfo loginInfo) {
		ContentValues data = new ContentValues();
		data.put("username", loginInfo.getUsername());
		data.put("password", loginInfo.getPassword());
		data.put("last_login_time", loginInfo.getLast_login_time());
		data.put("remember_password_flag", loginInfo.getRemember_password_flag());
		data.put("auto_login_flag", loginInfo.getAuto_login_flag());
		return _db.insert(TABLE_NAME, null, data) > 0;
	}
}
